//
//  WBOAuthViewController.swift
//  WeiBoApp
//
//  Created by James on 2017/7/9.
//  Copyright © 2017年 James. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {
    
    fileprivate lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", normalColor: UIColor.gray, highlightColor: UIColor.orange, target: self, action: #selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", normalColor: UIColor.gray, highlightColor: UIColor.orange, target: self, action: #selector(autoFill))
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppkey)&redirect_uri=\(WBRedirect_uri)"
        
        guard  let url = URL(string: urlStr) else {
            return
        }

         let request = URLRequest(url: url)
        
        webView.loadRequest(request)

    }
    
    ///自动填充- webview注入  直接通过js修改‘本地浏览器’中缓存的页面内容
    ///点击登录按钮，执行submit（） 将本地数据提交给服务器
    
    @objc fileprivate func autoFill(){
        //让webview执行js
        let js = "document.getElementById('userId').value = '13517832638';"+"document.getElementById('passwd').value = 'p@ssW0rd';"
        webView.stringByEvaluatingJavaScript(from: js)
    }
    
    @objc fileprivate func close(){
        dismiss(animated: true, completion: nil)
    }
    
    
    deinit {
        SVProgressHUD.dismiss()
    }
}

extension WBOAuthViewController:UIWebViewDelegate {
    
    /// webview将要加载请求
    ///
    /// - Parameters:
    ///   - webView: webview
    ///   - request: 将要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("加载-->\(request.url?.absoluteString)")
        //如果  字符串 包含 http://baidu.com  不加载
        //如果url中有 code 则授权成功
        
        guard let urlStr = request.url?.absoluteString else {
            return true
        }
        
        if urlStr .contains("http://baidu.com") && urlStr.contains("code="){
            
            let code  = request.url?.query?.substring(from: "code=".endIndex) ?? ""
            
            print("授权码 \(code)")
            
//            let str = urlStr as NSString
//            
//            let tokenCode = str.components(separatedBy: "code=").last! as String
            WBNetWorkManger.shared.loadAccessToken(code: code){(ret) in
                if !ret {
                    print("网络请求失败")
                    SVProgressHUD.show(withStatus: "网络请求失败")
                }
                
                
                //跳转界面 通过通知发送登录成功消息
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserLoginSuccessNotification), object: nil)
                
                
                SVProgressHUD.showSuccess(withStatus: "登录成功")
            }
            
            close()

            return false
        }
        
        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    

    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()

    }
    
}

